﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AhgoraParser.Library.Libs;
using System.Threading;

namespace AhgoraParser.Controllers
{
    public class CrawlerController : Controller
    {
        private static Dictionary<string, AhgoraWebCrawler> crawlersEmUso;
        static readonly object singletonSafeLocker = new object();
        static readonly object dictionaryLocker = new object();
        public static Dictionary<string, AhgoraWebCrawler> CrawlersEmUso
        {
            get
            {
                lock(singletonSafeLocker)
                {
                    if(crawlersEmUso == null) 
                    {
                        crawlersEmUso = new Dictionary<string, AhgoraWebCrawler>();
                    }
                }
                return crawlersEmUso;
            }
        }

        AhgoraWebCrawler crawler;
        AhgoraWebParser parser;
        public CrawlerController()
        {
            crawler = new AhgoraWebCrawler();
            crawler.AoReceberHtmlPagina += crawler_AoReceberHtmlPagina;
        }

        public AhgoraWebCrawler GetCrawlerInstace(string matricula) 
        {
            lock(CrawlersEmUso) 
            {
                AhgoraWebCrawler crawler;
                if(!CrawlersEmUso.ContainsKey( matricula ))
                {
                    crawler = new AhgoraWebCrawler();
                }
                else 
                {
                    crawler = CrawlersEmUso[matricula];
                }
                return crawler;
            }
        }

        void crawler_AoReceberHtmlPagina( string resposta )
        {
            parser = new AhgoraWebParser( resposta );
        }
        //
        // GET: /Crawler/
        public ActionResult Index()
        {
            return null;
        }

        [HttpPost]
        public ActionResult Logar( string login, string senha )
        {
            crawler.EfetuarLogin( login, senha );
            parser = new AhgoraWebParser( crawler.HtmlSite );
            return Json( parser.GetRegistros() );
        }
    }
}
